package com.dhy.domain;

import com.dhy.util.RabbitmqUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

import static com.dhy.constants.RabbitmqConstants.*;


/**
 * @author 大忽悠
 * @create 2022/5/19 18:59
 */
@Slf4j
public class ConsumerTwo implements Runnable{
    @Override
    public void run() {
        RabbitmqUtil rabbitmqUtil = null;
        try {
            rabbitmqUtil = new RabbitmqUtil("application.yml");
            Channel channel = rabbitmqUtil.createChannel();
            HashMap<String, Object> arguments = new HashMap<>();
            arguments.put("x-message-ttl",1000);
            channel.queueDeclare(Q2_QUEUE,false,false,false,arguments);
            channel.queueBind(Q2_QUEUE,TOPIC_EXCHANGE,Q2_ROUTE_KEY1);
            channel.queueBind(Q2_QUEUE,TOPIC_EXCHANGE,Q2_ROUTE_KEY2);

            channel.basicConsume(Q2_QUEUE,true,new DefaultConsumer(channel){
                @SneakyThrows
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    log.info("消息为: {}",new String(body));
                }
            });
        } catch (IOException | TimeoutException e) {
            log.error("出现异常: ",e);
        }
    }
}
